<template>
  <button class="lemon-switch" @click="toggle" :class="classes" :disabled="disabled">
    <span class="lemon-circle"></span>
    <slot name="open" v-if="value"></slot>
    <slot name="close" v-if="!value"></slot>
  </button>
</template>
<script lang="ts">
import { ref, computed } from "vue";
export default {
  props: {
    value: Boolean,
    size: {
      type: String,
      default: "normal",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    const { value, size } = props;
    const classes = computed(() => {
      return {
        "lemon-checked": props.value,
        [`lemon-switch-size-${size}`]: size,
      };
    });
    const toggle = () => {
      context.emit("update:value", !props.value);
    };
    return { classes, toggle };
  },
};
</script>

<style lang="scss">
$h: 22px;
$h2: $h - 4px;
$big_h: 30px;
$big_h2: $big_h - 4px;
$small_h: 15px;
$small_h2: $small_h - 4px;
.lemon-switch {
  & + & {
    margin-left: 50px;
  }
  height: $h;
  width: $h * 2.2;
  border: none;
  background: #bfbfbf;
  border-radius: $h/2;
  position: relative;
  > .lemon-circle {
    position: absolute;
    top: 2px;
    left: 2px;
    height: $h2;
    width: $h2;
    background: white;
    border-radius: $h2 / 2;
    transition: all 250ms;
  }
  &.lemon-checked {
    background: #1890ff;
    > .lemon-circle {
      left: calc(100% - #{$h2} - 2px);
    }
  }
  &[disabled] {
    cursor: not-allowed;
    background-color: #f3f3f3;
    .lemon-circle {
      background-color: #ccc;
    }
  }
  &:focus {
    outline: none;
  }
  &:active {
    > .lemon-circle {
      width: $h2 + 4px;
    }
  }
  &.lemon-checked:active {
    > .lemon-circle {
      width: $h2 + 4px;
      margin-left: -4px;
    }
  }
}
.lemon-switch-size-big {
  width: $big_h * 2.2;
  height: $big_h;
  border-radius: $big_h/2;
  > .lemon-circle {
    width: $big_h2;
    height: $big_h2;
    border-radius: $big_h2 / 2;
  }
  &.lemon-checked {
    > .lemon-circle {
      left: calc(100% - #{$big_h2} - 2px);
    }
  }
  &:active {
    > .lemon-circle {
      width: $big_h2 + 4px;
    }
  }
  &.lemon-checked:active {
    > .lemon-circle {
      width: $big_h2 + 4px;
      margin-left: -4px;
    }
  }
}
.lemon-switch-size-small {
  font-size: 12px;
  width: $small_h * 2.2;
  height: $small_h;
  border-radius: $small_h/2;
  > .lemon-circle {
    width: $small_h2;
    height: $small_h2;
    border-radius: $small_h2 / 2;
  }
  &.lemon-checked {
    > .lemon-circle {
      left: calc(100% - #{$small_h2} - 2px);
    }
  }
  &:active {
    > .lemon-circle {
      width: $small_h2 + 4px;
    }
  }
  &.lemon-checked:active {
    > .lemon-circle {
      width: $small_h2 + 4px;
      margin-left: -4px;
    }
  }
}
.close-text,
.open-text {
  color: white;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.close-text {
  right: 5px;
}
.open-text {
  left: 5px;
}
</style>